package top.heliming.youyou.item.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import top.heliming.youyou.common.pojo.PageResult;
import top.heliming.youyou.item.dao.BrandMapper;
import top.heliming.youyou.item.pojo.Brand;
import top.heliming.youyou.item.pojo.Category;
import top.heliming.youyou.item.service.BrandService;

/**
 * description: //TODO
 *
 * @author: heliming
 * @date:2019/05/27 下午 10:53
 */
@Service
public class BrandServiceImpl implements BrandService {
  @Autowired
  private BrandMapper brandMapper;

  @Override
  public PageResult<Brand> queryBrandByPageAndSort(Integer page, Integer rows, String sortBy,
      Boolean desc, String key) {
    // 开始分页
    PageHelper.startPage(page, rows);
    // 过滤
    Example example = new Example(Brand.class);
    if (StringUtils.isNotBlank(key)) {
      example.createCriteria().andLike("name", "%" + key + "%")
          .orEqualTo("letter", key);
    }
    if (StringUtils.isNotBlank(sortBy)) {
      // 排序
      String orderByClause = sortBy + (desc ? " DESC" : " ASC");
      example.setOrderByClause(orderByClause);
    }
    // 查询
    Page<Brand> pageInfo = (Page<Brand>) brandMapper.selectByExample(example);
    // 返回结果
    return new PageResult<>(pageInfo.getTotal(), pageInfo);
  }

  @Override
  @Transactional
  public void saveBrand(Brand brand, List<Long> cids) {
    // 新增品牌信息
    this.brandMapper.insertSelective(brand);
    // 新增品牌和分类中间表
    for (Long cid : cids) {
      this.brandMapper.insertCategoryBrand(cid, brand.getId());
    }
  }
@Override
  public List<Brand> queryBrandByCategory(Long cid) {
    return this.brandMapper.queryByCategoryId(cid);
  }
@Override
  public List<Brand> queryBrandByIds(List<Long> ids) {
    return this.brandMapper.selectByIdList(ids);
  }
}
